<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <el-icon><User /></el-icon>
          <span>个人信息</span>
        </div>
      </template>

      <el-form :model="userForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" disabled />
        </el-form-item>
        <el-form-item label="角色">
          <el-tag :type="userForm.role === 'admin' ? 'danger' : 'success'">
            {{ userForm.role === 'admin' ? '管理员' : '居民' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" :disabled="!isEditing" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userForm.phoneNumber" :disabled="!isEditing" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="formattedCreatedTime" disabled />
        </el-form-item>
        <el-form-item label="更新时间">
          <el-input v-model="formattedUpdateTime" disabled />
        </el-form-item>
        
        <el-form-item>
          <template v-if="!isEditing">
            <el-button type="primary" @click="startEdit">
              编辑信息
            </el-button>
          </template>
          <template v-else>
            <el-button type="primary" @click="saveChanges">
              保存
            </el-button>
            <el-button @click="cancelEdit">
              取消
            </el-button>
          </template>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <el-icon><Lock /></el-icon>
          <span>重置密码</span>
        </div>
      </template>

      <el-form :model="passwordForm" label-width="100px" :rules="passwordRules">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="changePassword">
            重置密码
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { getUserInfo } from '../api/api' // 确保已导入 getUserInfo 接口
import { updateResidentInfo, updatePassword } from '../api/api' // 确保已导入 updateResidentInfo 和 updatePassword 接口
import dayjs from 'dayjs'

const userForm = ref({
  userId: '',
  username: '',
  email: '',
  phoneNumber: '',
  role: '',
  createdAt: '',
  updatedAt: ''
})

const isEditing = ref(false)
const originalUserData = ref(null)

const formattedCreatedTime = computed(() => {
  return dayjs(userForm.value.createdAt).format('YYYY-MM-DD HH:mm:ss')
})

const formattedUpdateTime = computed(() => {
  return dayjs(userForm.value.updatedAt).format('YYYY-MM-DD HH:mm:ss')
})

const passwordForm = ref({
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const storedUserInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (storedUserInfo.userId) {
      const res = await getUserInfo(storedUserInfo.userId)
      if (res.code === 200 && res.data) {
        userForm.value = { ...res.data }
        originalUserData.value = { ...res.data }
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 开始编辑
const startEdit = () => {
  isEditing.value = true
}

// 取消编辑
const cancelEdit = () => {
  userForm.value = { ...originalUserData.value }
  isEditing.value = false
}

// 保存修改
const saveChanges = async () => {
  try {
    const updateData = {
      userId: userForm.value.userId,
      email: userForm.value.email,
      phoneNumber: userForm.value.phoneNumber
    }
    
    const res = await updateResidentInfo(updateData)
    if (res.code === 200) {
      ElMessage.success('保存成功')
      isEditing.value = false
      originalUserData.value = { ...userForm.value }
      
      // 更新本地存储的用户信息
      const storedUserInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      storedUserInfo.email = userForm.value.email
      storedUserInfo.phoneNumber = userForm.value.phoneNumber
      localStorage.setItem('userInfo', JSON.stringify(storedUserInfo))
    } else {
      ElMessage.error(res?.message || '保存失败')
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error('保存失败')
  }
}

// 修改密码
const changePassword = async () => {
  try {
    const passwordData = {
      username: userForm.value.username,
      email: userForm.value.email,
      newPassword: passwordForm.value.newPassword
    }
    
    const res = await updatePassword(passwordData)
    if (res.code === 200) {
      ElMessage.success('密码修改成功')
      passwordForm.value = {
        newPassword: '',
        confirmPassword: ''
      }
    } else {
      ElMessage.error(res?.message || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('密码修改失败')
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  display: grid;
  gap: 20px;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
}

.profile-card,
.password-card {
  height: fit-content;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.el-tag {
  text-transform: capitalize;
}
</style>